const dropArea = document.querySelector(".drag-area"),
dragText = dropArea.querySelector("header"),
button = dropArea.querySelector("button"),
input1 = document.querySelector(".file");

//保存上传文件
let file;

button.onclick = ()=>{
	input1.click();
}

input1.addEventListener("change",function(){
	file = this.files[0];
	showFile();
	dropArea.classList.add("active");
})


dropArea.addEventListener("dragover",(event)=>{
	// console.log("over");
	event.preventDefault();
	dropArea.classList.add("active");
	dragText.textContent = "Release to Upload File";
});

dropArea.addEventListener("dragleave",()=>{
	// console.log("leave");
	dropArea.classList.remove("active");
	dragText.textContent = "Drag to Upload File ";
})

dropArea.addEventListener("drop",(event)=>{
	// console.log("drop");
	event.preventDefault();
	//当多个文件传入时，只接受一个文件
	file = event.dataTransfer.files[0];
	showFile();
})

function showFile(){
	let fileType = file.type;
	// console.log(fileType);
	//接收的文件类型
	let validExtendsions = ["image/jpeg","image/png","image/jpg"];
	if(validExtendsions.includes(fileType)){
		let fileReader = new FileReader();
		
		fileReader.onload = ()=>{
			let fileURL = fileReader.result;
			let imgTag = '<img src="'+fileURL+'" alt="">';
			dropArea.innerHTML = imgTag;
		}
		fileReader.readAsDataURL(file);
	}else{
		alert("这不是图片文件！！！");
		dropArea.classList.remove("active");
	}
}